﻿using FreeSql;
using FreeSql.Aop;
using Microsoft.AspNetCore.Http;
using System.Reflection;
using System.Security.Claims;
using WebServer.Extensions;
using Wen.Core.Extensions;
using Yitter.IdGenerator;


namespace WebServer.Extensions;

public static class FreeSqlServiceExtension
{
    public static IServiceCollection AddFreeSqlServices(this IServiceCollection services)
    {
        IHttpContextAccessor httpContextAccessor = services.BuildServiceProvider().GetService<IHttpContextAccessor>()!;
        services.AddFreeSqlServices(provider =>
        {
            httpContextAccessor = provider.GetService<IHttpContextAccessor>()!;
            var configuration = provider.GetRequiredService<IConfiguration>();

            var connString = configuration.GetConnectionString("DefaultConnection");

            var dbType = Enum.TryParse(configuration.GetConnectionString("DbType"), out DataType result) ? result : DataType.Sqlite;

            return (dbType, connString!);
        }, fsql =>
        {
            fsql.Aop.AuditValue += (s, e) =>
            {
                if (e.AuditValueType == AuditValueType.Insert)
                {
                    if (e.Column.CsName == "CreateTime")
                    {
                        e.Value = DateTime.Now;
                    }
                    else if (e.Column.CsName == "CreateUserName")
                    {
                        e.Value = httpContextAccessor?.HttpContext?.User?.Identity?.Name ?? "System";
                    }
                }
                else if (e.AuditValueType == AuditValueType.Update)
                {
                    if (e.Column.CsName == "UpdateTime")
                    {
                        e.Value = DateTime.Now;
                    }
                    else if (e.Column.CsName == "UpdateUserName")
                    {
                        e.Value = httpContextAccessor?.HttpContext?.User?.Identity?.Name ?? "System";
                    }
                }

            };
        });
        return services;
    }
}
